import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useRef, forwardRef, useImperativeHandle, } from "react";
import { DevPopup } from "~/public/cpas-ui";
import { TextBox, TreeList } from "devextreme-react";
import AntTabs, { HocVerticalLeftStyleTab, } from "~/public/cpas-ui/components-ui/ant-components/AntTab";
import { AssistgetType, autoAddFirstChildren, getNewKMBH, getSubjectSDB, getSubjectType, } from "./DraftApi";
import { DevToolBar } from "~/public/cpas-ui";
import { Item } from "devextreme-react/toolbar";
import { Column } from "devextreme-react/tree-list";
import "./_style.less";
import notify from "devextreme/ui/notify";
import { CpasIcon } from "~/public/cpas-ui";
import { moneyFormat } from "../../../../CarryEntryPopup/components";
import { nanoid10 } from "../../../../../tools/Tools";
/**
 * ## 基于本地数据库，获取数据本地数据进行功能演示。
 * ~~~js
 * import AddPopup  from 'sright-ui'
 * ~~~
 */
export const AddPopup = forwardRef((props, ref) => {
    const [visible, setVisible] = useState(false);
    const [tabsData, setTabsData] = useState([]);
    const [SubjectSDBData, setSubjectSDBData] = useState([]);
    const [SubjectSDBDatas, setSubjectSDBDatas] = useState([]);
    const [selectMode, setSelectMode] = useState("");
    const [TbsStates, setTbsStates] = useState("0");
    const [value, setValue] = useState("");
    const diaParams = useRef();
    const selectRowData = useRef();
    const AddPopupTreeListRef = useRef();
    const typeRef = useRef();
    // 选中行状态
    const [selectState, setSelectState] = useState(true);
    const curNodeRef = useRef();
    const [curRowKMMC, setCurRowKMMC] = useState("");
    const [treeListKey, setTreeListKey] = useState("");
    // 获取切换数据
    const getSubjectTypeData = async () => {
        const res = await getSubjectType({
            dbname: diaParams.current?.dbname,
            Data_ID: diaParams.current?.Data_ID,
        });
        if (res.success) {
            res.data.unshift({ code: "0", type: "全部" });
            setTabsData(res.data);
        }
        else {
            setTabsData([]);
        }
    };
    const tableScrollTo0 = () => {
        setTreeListKey(nanoid10());
        setValue("");
        AddPopupTreeListRef.current.instance.searchByText();
        AddPopupTreeListRef?.current?.instance?.clearSelection();
        // const leftTreeViewScrollView =
        //   AddPopupTreeListRef?.current?.instance?.getScrollable();
        // if (leftTreeViewScrollView) {
        //   // leftTreeViewScrollView.scrollTop();
        //   setValue("");
        //   AddPopupTreeListRef.current.instance.searchByText();
        //   AddPopupTreeListRef?.current?.instance?.clearSelection();
        //   leftTreeViewScrollView.scrollTo({ left: 0, top: 0 });
        // }
    };
    // 获取表格数据
    const getSubjectSDBDatas = async () => {
        const res = await getSubjectSDB({
            dbname: diaParams.current?.dbname,
            Data_ID: diaParams.current?.Data_ID,
            isHasFZZ: diaParams.current?.isHasFZZ,
        });
        if (res.success) {
            setSubjectSDBData(res.data);
            setSubjectSDBDatas(res.data);
        }
        else {
            setSubjectSDBData([]);
            setSubjectSDBDatas([]);
        }
        tableScrollTo0();
    };
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: async (params) => {
            diaParams.current = params;
            setVisible(true);
            setSelectState(true);
            setSelectMode(diaParams.current?.selectMode);
            getSubjectSDBDatas();
            getSubjectTypeData();
        },
    }));
    // 标签页过滤表格数据
    const getSubjectListData = async (val) => {
        tableScrollTo0();
        if (val === "全部") {
            if (SubjectSDBData?.length)
                setSubjectSDBDatas(SubjectSDBData);
        }
        else {
            if (SubjectSDBData?.length) {
                const KMLXData = SubjectSDBData.filter((item) => {
                    return item.KMLX && item.KMLX.includes(val);
                });
                setSubjectSDBDatas(KMLXData);
            }
        }
    };
    const AccountTabsClick = (val) => {
        setTbsStates(val);
        const resF = tabsData.filter((item) => val === item.code);
        getSubjectListData(resF[0]?.type ?? "全部");
    };
    const onCellClick = (e) => {
        console.log(e.data, selectMode, "@@@");
        if (selectMode === "0") {
            selectRowData.current = e.data;
        }
        else {
            const v = AddPopupTreeListRef.current.instance.getSelectedRowsData("all");
            selectRowData.current = v;
        }
    };
    const GetautoAddFirstChildren = async (data) => {
        console.log(data, "-----");
        let paramsObj = {
            dbname: diaParams.current?.dbname,
            Data_ID: diaParams.current?.Data_ID,
            editUser: diaParams.current?.editUser,
        };
        if (selectRowData.current?.PID === "0") {
            paramsObj = {
                ...paramsObj,
                KMBH: selectRowData.current.KMBH,
            };
        }
        else {
            paramsObj = {
                ...paramsObj,
                KMBH: data.KMBH,
            };
        }
        await autoAddFirstChildren(paramsObj);
        const res = await getNewKMBH(paramsObj);
        if (res.ok) {
            diaParams.current?.okCallback(data, res.data);
        }
    };
    // // 判断是否可以增加辅助账
    async function IsCanAddFZZStates_okCallback(v, KMBH) {
        if (v[0].code === 1) {
            setVisible(false);
            const res = await AssistgetType({
                dbname: diaParams.current?.dbname,
                Data_ID: diaParams.current?.Data_ID,
                KMBH: KMBH,
            });
            console.log(selectRowData.current, res, "selectRowData.current, r------");
            if (res.ok) {
                // 后期会在调一个 自动生成挂辅助账的科目名称 传给第一个参数
                diaParams.current?.okCallback(selectRowData.current, res.data);
            }
        }
    }
    const okCallback_function = async (rowData) => {
        if (!diaParams.current?.okCallback)
            return notify("传入的okCallback出错", "error", 2000);
        if (!rowData)
            return notify("请选择您要选择的科目", "warning", 2000);
        // 是否可以选择上级科目
        if (diaParams.current?.isSelectSuperior) {
            // 科目 判断 是否为末级
            if (rowData?.isEnd) {
                typeRef.current.show({
                    title: "提示",
                    okCallback: () => {
                        setVisible(false);
                        GetautoAddFirstChildren(rowData);
                    },
                });
            }
            else {
                // 如果不是末级 直接返回参数 和关闭弹出框
                setVisible(false);
                const res = await getNewKMBH({
                    dbname: diaParams.current?.dbname,
                    Data_ID: diaParams.current?.Data_ID,
                    KMBH: rowData.KMBH,
                });
                if (res.ok) {
                    diaParams.current?.okCallback(rowData, res.data);
                }
            }
        }
        else {
            // 科目 判断 是否为末级
            if (rowData?.isEnd) {
                setVisible(false);
                diaParams.current?.okCallback(rowData, "");
            }
            else {
                notify("非末级结点科目,无法选中!", "error", 2000);
            }
        }
        // setValue("");
        // setTbsStates("0");
        // AddPopupTreeListRef.current.instance.searchByText();
        // AddPopupTreeListRef.current.instance.clearSelection();
    };
    // 双击事件
    const onCellDblClick = async (e) => {
        const rowData = e.data;
        selectRowData.current = e.data;
        setCurRowKMMC(rowData.KMMC);
        await okCallback_function(rowData);
    };
    // 按钮 确定事件
    const ok = async () => {
        const getrowdata = AddPopupTreeListRef.current.instance.getSelectedRowsData();
        selectRowData.current = getrowdata[0];
        setCurRowKMMC(getrowdata[0]?.KMMC ?? "");
        await okCallback_function(selectRowData.current);
    };
    function convertToTree(data) {
        let result = [];
        if (!Array.isArray(data)) {
            return result;
        }
        let map = {};
        data.forEach((item) => {
            delete item.children;
            map[item.ID] = item;
        });
        data.forEach((item) => {
            let parent = map[item?.PID ?? ""];
            if (parent) {
                (parent.children || (parent.children = [])).push(item);
            }
            else {
                result.push(item);
            }
        });
        return result;
    }
    // 模糊搜索
    const inputSearch = (content) => {
        AddPopupTreeListRef.current.instance.searchByText(content || "");
    };
    // const throttleSearch = throttle(inputSearch, 100);
    const getInputValue = (e) => {
        const { event } = e;
        inputSearch(event.target.value);
        setValue(event.target.value);
    };
    const closePopup = () => {
        setValue("");
        setVisible(false);
        setTbsStates("0");
        AddPopupTreeListRef.current.instance.searchByText();
        AddPopupTreeListRef.current.instance.clearSelection();
    };
    return (_jsxs(_Fragment, { children: [_jsx(DevPopup.Logic, { ref: ref, width: 1000, height: 700, visible: visible, title: diaParams.current?.title, onOK: ok, onCancel: () => {
                    closePopup();
                }, onHiding: () => {
                    closePopup();
                }, children: () => {
                    return (_jsxs("div", { style: { width: "100%", height: "100%" }, children: [_jsx("div", { style: { display: "flex" }, children: _jsxs(DevToolBar.Default, { className: "ItemStyle", children: [_jsx(Item, { location: "before", children: _jsx("div", { style: {
                                                    display: "flex",
                                                    alignItems: "center",
                                                    marginLeft: "65px",
                                                }, children: _jsx("span", { style: { color: "red" }, children: "\u63D0\u793A\uFF1A\u53CC\u51FB\u53EF\u9009\u4E2D\u76F8\u5E94\u79D1\u76EE" }) }) }), _jsx(Item, { location: "after", children: _jsxs("div", { style: {
                                                    display: "flex",
                                                    alignItems: "center",
                                                    marginBottom: "10px",
                                                    marginLeft: "20px",
                                                }, children: [_jsx("span", { style: { marginRight: "15px" }, children: _jsx(TextBox, { onInput: (e) => getInputValue(e), width: 200, value: value, className: "TextBoxButtons_Style", buttons: [
                                                                {
                                                                    location: "before",
                                                                    name: "search",
                                                                    options: {
                                                                        icon: "iconfont icon-search",
                                                                        disabled: true,
                                                                    },
                                                                },
                                                            ] }) }), _jsx("span", { className: "refresh_Style", children: _jsx(CpasIcon, { fontSize: 15, type: "icon-refresh", onClick: () => {
                                                                getSubjectSDBDatas();
                                                                getSubjectTypeData();
                                                                setTbsStates("0");
                                                            } }) })] }) })] }) }), _jsxs("div", { style: { display: "flex", height: "92%" }, children: [_jsx("div", { style: { border: "1px solid #ddd", borderRight: "none" }, children: _jsx(HocVerticalLeftStyleTab, { activeKey: TbsStates, className: "SubjectsTabs", tabPosition: "left", tabBarStyle: { background: "#FFF" }, onChange: AccountTabsClick, children: Array.isArray(tabsData)
                                                ? tabsData.map((item) => {
                                                    return (_jsx(AntTabs.Panel, { tab: item.type, style: { marginTop: "5px" } }, item.code));
                                                })
                                                : "" }) }), _jsxs(TreeList, { selection: {
                                            recursive: true,
                                            mode: selectMode === "0" ? "single" : "multiple",
                                        }, className: "PublicTreeList devHeadersCenter", ref: AddPopupTreeListRef, dataSource: SubjectSDBDatas, allowColumnResizing: true, showBorders: true, showRowLines: true, 
                                        // allowColumnResizing={true}
                                        // columnAutoWidth={true}
                                        // showRowLines={true}
                                        // showBorders={true}
                                        columnResizingMode: "widget", columnMinWidth: 100, parentIdExpr: "PID", keyExpr: "ID", id: "Code", width: "95%", height: "100%", onCellClick: onCellClick, 
                                        // onContentReady={contentReady}
                                        onCellDblClick: onCellDblClick, onSelectionChanged: () => {
                                            console.log("触发----------");
                                            setSelectState(false);
                                        }, 
                                        // 显示斑马线
                                        rowAlternationEnabled: true, children: [_jsx(Column, { dataField: "code", caption: "\u79D1\u76EE\u7F16\u53F7", width: 130, alignment: "left" }), _jsx(Column, { dataField: "KMMC", caption: "\u79D1\u76EE\u540D\u79F0", width: 200, alignment: "left" }), _jsx(Column, { dataField: "KMFX", caption: "\u79D1\u76EE\u65B9\u5411", width: 80, alignment: "center" }), _jsx(Column, { dataField: "QCYE", caption: "\u671F\u521D\u4F59\u989D", width: 120, alignment: "right", cellRender: (cell) => {
                                                    return cell.data.QCYE ? moneyFormat(cell.data.QCYE) : "";
                                                } }), _jsx(Column, { dataField: "JFLJFSE", caption: "\u501F\u65B9\u7D2F\u8BA1", width: 130, alignment: "right", cellRender: (cell) => {
                                                    return cell.data.JFLJFSE
                                                        ? moneyFormat(cell.data.JFLJFSE)
                                                        : "";
                                                } }), _jsx(Column, { dataField: "DFLJFSE", caption: "\u8D37\u65B9\u7D2F\u8BA1", width: 130, alignment: "right", cellRender: (cell) => {
                                                    return cell.data.DFLJFSE
                                                        ? moneyFormat(cell.data.DFLJFSE)
                                                        : "";
                                                } }), _jsx(Column, { dataField: "QMYE", caption: "\u671F\u672B\u4F59\u989D", width: 130, alignment: "right", cellRender: (cell) => {
                                                    return cell.data.QMYE ? moneyFormat(cell.data.QMYE) : "";
                                                } }), _jsx(Column, { dataField: "itemNames2", caption: "\u62A5\u8868\u9879\u76EE", width: 130, alignment: "left" })] }, treeListKey)] })] }));
                } }), _jsx(DevPopup.Default, { ref: typeRef, children: () => {
                    //
                    return (_jsx("span", { children: `科目【${curRowKMMC}】为末级科目，是否继续为其增加下级科目` }));
                } })] }));
});
export default React.memo(AddPopup);
